<?php

/**
 * Controller/MutuelleController.php
 */

namespace RHX\Controller;

class MutuelleController extends RHXController {

    public function indexAction() {
	//
    }

    /**
     * Chargement du contenu de la page d'accueil
     *
     * @return array
     */
    public function loadIndexAction() {
	// Changement de layout
	$this->layout('layout/ajax');
	// table mutuelle
	$mutuelleTable = new \RHX\Model\Table\MutuelleTable($this->getAdapter());

	// Liste des titres
	$mutuelles = $mutuelleTable->getAll();

	return array(
	    'mutuelles' => $mutuelles,
	);
    }

    /**
     * Ajouter en JSON
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function addAction() {
	// POST
	$post = $this->getRequest()
		->getPost();

	// Nouveau
	$mutuelle = new \RHX\Model\Object\Mutuelle($post);

	// Table  Séjour
	$mutuelleTable = new \RHX\Model\Table\MutuelleTable($this->getAdapter());

	$id	 = 0;
	$err	 = null;

	try {
	    $id = $mutuelleTable->save($mutuelle);
	}
	catch (\Exception $ex) {
	    $err = $ex;
	}

	return new \Zend\View\Model\JsonModel(array(
	    'done'	 => (is_null($err)) ? true : false,
	    'error'	 => $err,
	    'id'	 => $id,
	));
    }

    /**
     * Sauvegarde des données via X-editable
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function saveStringAction() {
	// POST
	$post = $this->getRequest()
		->getPost();

	$pk	 = $post->pk;
	$name	 = $post->name;
	$value	 = addslashes($post->value);

	$sql	 = "UPDATE rh_mutuelle SET $name = '$value' WHERE id = $pk";
	$adapter = $this->getAdapter();
	$result	 = $adapter->query($sql)->execute();

	$done = false;

	if ($result) {
	    $done = true;
	}

	return new \Zend\View\Model\JsonModel(array(
	    'done' => $done,
	));
    }

    public function saveIntAction() {
	// POST
	$post = $this->getRequest()
		->getPost();

	$pk	 = $post->pk;
	$name	 = $post->name;
	$value	 = addslashes($post->value);

	$sql	 = "UPDATE rh_mutuelle SET $name = $value WHERE id = $pk";
	$adapter = $this->getAdapter();
	$result	 = $adapter->query($sql)->execute();

	$done = false;

	if ($result) {
	    $done = true;
	}

	return new \Zend\View\Model\JsonModel(array(
	    'done' => $done,
	));
    }

    /**
     * Effacer une mutuelle
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function eraseAction() {
	// changement de layout
	$this->layout('layout/ajax');
	// post
	$post	 = $this->getRequest()
		->getPost();
	// table
	$table	 = new \RHX\Model\Table\MutuelleTable($this->getAdapter());
	$nb	 = $table->erase($post->id);

	return new \Zend\View\Model\JsonModel(array(
	    'nb'	 => $nb,
	    'done'	 => ($nb > 0) ? true : false,
	));
    }

}

?>
